package org.tsp.android.SensorExample;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.tsp.android.SensorExample.R;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.ExifInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class SensorSlideShow extends Activity implements SensorEventListener, LocationListener {
	
	private SensorManager m_sensorMngr;
	private Sensor m_acc;
	
	private LocationManager m_locMngr;
	
	private Boolean switched = false;
	
	private int image_index;
	
	private String last_image; 
	private Bitmap last_bitmap;
	private Boolean location_fixed = false;
	
	private double location_lat = 0; 
	private double location_lng = 0;
	private double location_alt = 0;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.slide_show);
        
    }
    
    @Override
    public void onStart()
    {	
    	super.onStart();
    	
    	m_sensorMngr = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        m_acc = m_sensorMngr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        
        // To complete
        // Use asset manager and load the first image
        
        m_locMngr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    }
    
    @Override
    public void onResume()
    {
    	super.onResume();
    	m_sensorMngr.registerListener(this, m_acc, SensorManager.SENSOR_DELAY_NORMAL);
    	m_locMngr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    }
    
    @Override
    public void onPause()
    {
    	super.onPause();
    	m_sensorMngr.unregisterListener(this);
    	m_locMngr.removeUpdates(this);
    }
    
    @Override
    public void onStop()
    {
    	super.onStop();
    	
    	m_acc = null;
    }
    
    private String latLngToExif(double num)
    {
    	String res = "";
    	int deg, min, sec, secDiv;
    	double tmp;
    	
    	deg = (int) Math.floor(Math.abs(num));
    	tmp = (Math.abs(num) - Math.floor(Math.abs(num))) * 60;
    	min = (int) Math.floor(tmp);
    	tmp = (tmp - Math.floor(tmp)) * 60 * 1000;
    	sec = (int) Math.floor(tmp);
    	
    	res += deg + "/1,";
    	res += min + "/1,";
    	res += sec + "/1000";
    	
    	return res;
    }
    
    public void tagImageClick(View v)
    {
    	if (!location_fixed)
    	{
    		Toast t = Toast.makeText(this, "GPS Location not fixed yet. Wait for the icon to stop blinking.", Toast.LENGTH_SHORT);
    		t.show();
    		return;
    	}
    	String image_file = "/sdcard/media/"+last_image;
    	// To complete
    	// Save last image to file 
    	
    	try {
			String lat = latLngToExif(location_lat);
			String lat_ref = "N";
			if (location_lat < 0)
				lat_ref = "S";
			
			String lng = latLngToExif(location_lng);
			String lng_ref = "E";
			if (location_lng < 0)
				lat_ref = "W";
			
			//To complete
			// Save GPS to Exif Data
			
			Toast t = Toast.makeText(this, "GPS Data Set", Toast.LENGTH_SHORT);
    		t.show();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    public void setAcceleration(float x, float y, float z)
    {
    	if ( z < 7 )
    	{
    		if ( !switched )
    		{
    			switched = true;
    			// To complete
    			// Use asset manager to load next or previous image
    		}
    	}
    	else
    		if ( switched )
    			switched = false;
    }
    
    private void loadImageAssets(String image)
    {
    	AssetManager assetManager = getAssets();
    	InputStream inputStream = null;
    	
    	try {
			inputStream = assetManager.open(image);
			loadImage(inputStream);
			inputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    }
    
    private void loadImage(InputStream img_stream)
    {
    	final ImageView img = (ImageView) findViewById(R.id.img_view);
    	last_bitmap = BitmapFactory.decodeStream(img_stream);
		this.runOnUiThread(new Runnable(){

			public void run() {
				// TODO Auto-generated method stub
				img.setImageBitmap(last_bitmap);
			}
			
		});
    }

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		setAcceleration(event.values[0], event.values[1], event.values[2]);
	}

	@Override
	public void onLocationChanged(Location location) {
		location_fixed = true;
		// To complete
		// Handle locaton updates here
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}

}
